<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
    <style>
        .container h2 {
            border-bottom: 2px solid #F5F5F5;
            padding-bottom: 10px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2>Promise发送AJAX请求</h2>
        <button id="sendAjax">发送AJAX</button>
    </div>
</body>

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
    const url = 'https://api.apiopen.top/getJoke';
    // 第一种方式：纯 AJAX
    // $('#sendAjax').click(() => {
    //     $.get(url, (data, status) => {
    //         console.log(data);
    //         console.log(status);
    //     });
    // });AJAX

    // 第二种方式：Promise封装
    function http(url, type, data) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url,
                type,
                data,
                success: (ret) => {
                    if (!ret)
                        reject({ state: false, message: '接口请求失败' });
                    else
                        resolve(ret);
                },
                error: (err) => {
                    reject(err);
                }
            });
        });
    }

    $('#sendAjax').click(() => {
        http(url, 'GET').then(ret => console.log(ret), err => console.log(err));
    });
</script>

</html>